using System.Collections.Generic;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using System.Diagnostics;

namespace Solutionizing.ProfileMySiteRedirect
{
    public class ProfileMySiteRedirectControl : UserControl, IFormDelegateControlSource
    {
        public void OnFormInit(object objOfInterest)
        {
            var user = objOfInterest as SPListItem;
            if (user != null)
                // The user list's Account field is the built-in Name site column
                RedirectIfNecessary(user[SPBuiltInFieldId.Name] as string);
        }

        public void OnFormSave(object objOfInterest) { }

        protected void RedirectIfNecessary(string user)
        {
            try
            {
                if (string.IsNullOrEmpty(user))
                    return;

                bool force = false;
                if (bool.TryParse(Request.QueryString["Force"], out force) && force)
                    return;

                var sc = ServerContext.Current;
                if (sc == null)
                    return;

                var mgr = new UserProfileManager(sc);
                if (mgr != null && mgr.UserExists(user))
                    Response.Redirect(mgr.MySiteHostUrl.Trim('/') + "/Person.aspx?accountname=" + user);
            }
            catch (SPException) { }
        }
    }
}